package cn.myplus.blog.catalog.controller;

import cn.myplus.apiversion.ApiVersion;
import cn.myplus.blog.catalog.CatalogService;
import cn.myplus.blog.catalog.dto.CatalogDto;
import cn.myplus.blog.response.ResponseEntityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 目录接口.
 *
 * @author libo.
 * @date 2022/5/29
 */
@RestController
@RequestMapping(value = CatalogController.PATH)
public class CatalogController {

    public final static String PATH = "/catalogs";

    private final Logger logger = LoggerFactory.getLogger(CatalogController.class);

    @Autowired
    private CatalogService catalogService;

    @PostMapping()
    public ResponseEntity createCatalog(@RequestBody CatalogDto catalog) {
        if (catalog == null || "".equals(catalog.getId())) {
            throw new IllegalArgumentException("请求参数错误");
        }
        CatalogDto result = new CatalogDto();
        result = catalog;
        result.setLink(PATH + "/" + catalog.getId());
        catalogService.save(result);
        return ResponseEntityUtil.created(catalog);
    }

    @GetMapping("/{catalog_id}")
    public ResponseEntity getCatalog(@PathVariable("catalog_id") String catalogId) {
        CatalogDto dto = new CatalogDto();
        dto.setId(catalogId);
        dto.setLink(PATH + "/" + catalogId);
        dto.setName("单个目录");
        return ResponseEntityUtil.ok(dto);
    }

    @ApiVersion(ApiVersion.V2)
    @GetMapping("/{catalog_id}")
    public ResponseEntity getCatalogV2(@PathVariable("catalog_id") String catalogId) {
        CatalogDto dto = new CatalogDto();
        dto.setId(catalogId);
        dto.setLink(PATH + "/" + catalogId);
        dto.setName("单个目录V2");
        return ResponseEntityUtil.ok(dto);
    }

    @GetMapping()
    public ResponseEntity listCatalog(@RequestBody CatalogDto catalog) {
        List<CatalogDto> catalogDtos = mockCatalogs();

        return ResponseEntityUtil.listWithPage(catalogDtos);

    }

    List<CatalogDto> mockCatalogs() {
        ArrayList<CatalogDto> catalogDtos = new ArrayList<CatalogDto>();
        for (int i = 0; i < 10; i++) {
            CatalogDto dto = new CatalogDto();
            dto.setId(UUID.randomUUID().toString());
            dto.setName("名称" + i);
            dto.setLink(PATH + "/" + dto.getId());
            catalogDtos.add(dto);
        }
        return catalogDtos;
    }
}
